package com.dayangxiaoen.utils;

import com.alibaba.fastjson.JSON;
import com.dayangxiaoen.pojo.*;
import org.apache.tomcat.jni.Time;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author dayangxiaoen
 */
public class HttpUtils {



    public static void getBiliBiliMarketItems(String cookie) throws InterruptedException {
        LinkedList<Item> items = new LinkedList<Item>();

        ResponseData response = getResponse("null", cookie);

        items.addAll(response.getData().getData());

        while (response.getData().getNextId() != null){

            Thread.sleep(5000);

            response = getResponse(response.getData().getNextId(), cookie);

            System.out.println("nextId为：" + response.getData().getNextId());

            if(response.getData() != null){
                if(response.getData().getData() != null){
                    items.addAll(response.getData().getData());
                }else {
                    break;
                }
            }else {
                break;
            }

        }

        List<Item> collect = items.stream().filter(item -> item.getC2cItemsName().contains("芙莉莲")).collect(Collectors.toList());

        System.out.println(collect);

    }

    /**
     * 获取每次请求的 ResponseData
     */
    public static ResponseData getResponse(String nextId, String cookie){

        ResponseData responseData = null;

        try {

            // 请求路径
            URL url = new URL("https://mall.bilibili.com/mall-magic-c/internet/c2c/v2/list"); // 替换为你的URL
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            conn.setRequestMethod("POST");

            // 设置请求头
            conn.setRequestProperty("Cookie", cookie);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Mobile Safari/537.36");


            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);

            ArrayList<String> prices = new ArrayList<>();
            prices.add("20000-0");

            ListParam listParam = new ListParam("PRICE_ASC", "2312", nextId,prices);
            String jsonString = JSON.toJSONString(listParam);

            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(jsonString.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();

            // 获取响应码
            int responseCode = conn.getResponseCode();
            System.out.println("POST Response Code :: " + responseCode);

            // 接收响应
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder response = new StringBuilder();

                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }

                reader.close();
                inputStream.close();

                responseData = JSON.parseObject(response.toString(), ResponseData.class);
                System.out.println(responseData);
                System.out.println("===========查找芙芙手办========");

                List<Item> collect = responseData.getData().getData().stream().filter(item -> item.getC2cItemsName().contains("芙莉莲")).collect(Collectors.toList());
                System.out.println(collect);

                // 对获得到的数据进行处理
                // 名称 实际价格 售卖价格 图片

                // 判断当前 collect 是否为空
                if(!collect.isEmpty() && collect != null){
                    collect.forEach((item -> {
                        ItemReduce itemReduce = new ItemReduce();
                        itemReduce.setName(item.getC2cItemsName());
                        itemReduce.setShowPrice(Double.parseDouble(item.getShowPrice()));
                        itemReduce.setShowMarketPrice(Double.parseDouble(item.getShowMarketPrice()));
                        itemReduce.setImg(item.getUface());

                        // 添加进缓存
                    }));



                }



                System.out.println("==============分页=============");

            } else {
                System.out.println("request not worked");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return responseData;
    }

}
